package com.gpt.article.service.impl.taskHandle;

import com.dataprocessor.DefaultDataProcessor;
import com.dataprocessor.provider.DataProvider;
import com.dataprocessor.provider.LongSliceDataProvider;
import com.dataprocessor.provider.Page;
import com.dataprocessor.slice.Slice;
import com.gpt.article.domain.GptTopicTitle;
import com.gpt.article.service.IGptTopicTitleService;
import com.gpt.article.service.ITxtClassifyService;
import com.gpt.article.service.impl.GptTopicTitleServiceImpl;
import com.gpt.article.service.impl.taskHandle.task.GenTopicTasker;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 适合用于大批量/全量  任务分批执行
 *  主要是分割id
 *
 */
@Service
public class TaskSplite {

    private static Logger logger = LoggerFactory.getLogger(TaskSplite.class);
    //任务处理对象的id
    private List<Long> source;
//    private List<Long> target;
    //间隔
    private Integer span;
    //任务类型  topic/主题大纲生成内容， xigao/洗稿
    private String taskType;

    private String acc;

    private Map<String,Object> psMap;

    private static IGptTopicTitleService gptTopicTitleService;

    private static ITxtClassifyService txtClassifyService;
    @Autowired
    public void setIGptTopicTitleService(IGptTopicTitleService gptTopicTitleService) {
        TaskSplite.gptTopicTitleService = gptTopicTitleService;
    }
    @Autowired
    public void setITxtClassifyService(ITxtClassifyService txtClassifyService) {
        TaskSplite.txtClassifyService = txtClassifyService;
    }

    public Map<String, Object> getPsMap() {
        return psMap;
    }

    public void setPsMap(Map<String, Object> psMap) {
        this.psMap = psMap;
    }


    /**
     * 任务配置
     * @throws Exception
     */
    public static class Builder {
        private TaskSplite taskSplite = new TaskSplite();
        /**
         * 执行对象id
         * @param source
         * @return
         */
        public Builder setSource(List<Long> source){
            taskSplite.source = source;
            return this;
        }
        /**
         * 任务创建者
         * @param acc
         * @return
         */
        public Builder setAcc(String acc){
            taskSplite.acc = acc;
            return this;
        }
        public Builder setPsMap(Map<String,Object> psMap){
            taskSplite.psMap = psMap;
            return this;
        }

        /**
         * 间隔 最好设置128
         * @param span
         * @return
         */
        public Builder setSpan(Integer span){
            taskSplite.span = span;
            return this;
        }
        /**
         * 分批数据类型
         * @param taskType
         * @return
         */
        public Builder setTaskType(String taskType){
            taskSplite.taskType = taskType;
            return this;
        }

        public TaskSplite build() {
            return taskSplite;
        }

    }


    //启动任务
    public void process() {
        DataProvider<Long, Long> provider = new MockDataProvider();
        DefaultDataProcessor migrator = new DefaultDataProcessor<>(provider);
        migrator.setLaunchInterval(0);
        migrator.process();
    }

    //断点继续任务，可以继续上次任务
    public void resumeProgress() {
        DataProvider<Long, Long> provider = new MockDataProvider();
        DefaultDataProcessor migrator = new DefaultDataProcessor<>(provider);
        migrator.setLaunchInterval(0);
        migrator.resumeProgress();
    }


    private class MockDataProvider extends LongSliceDataProvider<Long> {
        private int pageSize = 200;

        public MockDataProvider() {
            super(0, source.size(), span, true);
        }

        @Override
        public Page<Long> getResources(Slice<Long> slice, Page<Long> lastPage) throws Exception {
            int start = slice.getBegin().intValue();
            int currentPage = 0;
            if (lastPage != null) {
                currentPage = lastPage.getCurrentPage() + 1;
            }
            start += currentPage * pageSize;
            int end = start + pageSize;
            return new Page<>(end < slice.getEnd(), source.subList(start,
                    Math.min(end, slice.getEnd().intValue())), pageSize, currentPage);
        }

        /**
         * 任务处理逻辑
         * @param resources 本批次需要处理的资源
         * @return
         */
        @Override
        public Callable<?> createTask(List<Long> resources) {
            return (Callable<Object>) () -> {
                logger.info("本次分批处理数：{}",resources.size());
                Long[] taskObjId = resources.toArray(new Long[resources.size()]);
                if("topic".equals(taskType)){
                     gptTopicTitleService.genGptTopic(taskObjId,getAcc());
                     //每次分片任务间隔一秒缓解服务器压力
                     Thread.sleep(528);
                }

                if("txtClassify".equals(taskType)){
//                    for(Long li:taskObjId){
//                        System.out.println(li+"~~~");
//                    }
//                    System.out.println(getPsMap()+"~~~");
                    txtClassifyService.genGptClassify(taskObjId,getAcc(),getPsMap());
                    //每次分片任务间隔一秒缓解服务器压力
                    Thread.sleep(528);
                }


//                for (Long resource : resources) {
//                    Long r = resource;
                    // 处理可能出现的重复数据（失败重试时会有）
//                    if (!target.contains(r)) {
//                        target.add(r);
//                    }
//                }
                return true;
            };
        }
    }

    public String getTaskType() {
        return taskType;
    }

    public void setTaskType(String taskType) {
        this.taskType = taskType;
    }
    public String getAcc() {
        return acc;
    }

    public void setAcc(String acc) {
        this.acc = acc;
    }
}
